package com.itcam.lease.web.app.service.impl;

import com.itcam.lease.model.entity.BrowsingHistory;
import com.itcam.lease.web.app.mapper.BrowsingHistoryMapper;
import com.itcam.lease.web.app.mapper.RoomInfoMapper;
import com.itcam.lease.web.app.service.BrowsingHistoryService;
import com.itcam.lease.web.app.vo.history.HistoryItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
@Slf4j
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {

    @Autowired
    private BrowsingHistoryMapper browsingHistoryMapper;


    /**
     * 获取浏览历史
     * @param page
     * @param userId
     * @return
     */
    @Override
    public IPage<HistoryItemVo> pageHistoryItemByUserId(Page<HistoryItemVo> page, Long userId) {
        return browsingHistoryMapper.pageHistoryItemByUserId(page, userId);
    }

    /**
     * 保存浏览历史
     * @param userId 用户ID
     * @param roomId 房间ID
     */
    @Override
    @Async // 保存浏览历史的动作不应影响前端获取房间详情信息，故此处采取异步操作
    public void saveHistory(Long userId, Long roomId) {
        // 创建一个查询包装器，用于构建查询条件
        LambdaQueryWrapper<BrowsingHistory> queryWrapper = new LambdaQueryWrapper<>();
        // 添加查询条件，用户ID等于传入的userId
        queryWrapper.eq(BrowsingHistory::getUserId, userId);
        // 添加查询条件，房间ID等于传入的roomId
        queryWrapper.eq(BrowsingHistory::getRoomId, roomId);
        // 根据查询条件查询数据库，返回一个浏览历史记录
        BrowsingHistory browsingHistory = browsingHistoryMapper.selectOne(queryWrapper);
        // 如果查询到的浏览历史记录不为空
        if (browsingHistory != null) {
            // 更新浏览历史记录的浏览时间为当前时间
            browsingHistory.setBrowseTime(new Date());
            // 更新数据库中的浏览历史记录
            browsingHistoryMapper.updateById(browsingHistory);
        } else {
            // 如果查询到的浏览历史记录为空，则创建一个新的浏览历史记录对象
            BrowsingHistory newBrowsingHistory = new BrowsingHistory();
            // 设置新浏览历史记录的用户ID为传入的userId
            newBrowsingHistory.setUserId(userId);
            // 设置新浏览历史记录的房间ID为传入的roomId
            newBrowsingHistory.setRoomId(roomId);
            // 设置新浏览历史记录的浏览时间为当前时间
            newBrowsingHistory.setBrowseTime(new Date());
            // 将新浏览历史记录插入数据库
            browsingHistoryMapper.insert(newBrowsingHistory);
        }
    }

}




